package com.gombe.credit.app.common

import android.os.Bundle
import android.view.View
import com.gombe.credit.app.GombeCreditApp
import com.gombe.credit.app.R
import com.gombe.credit.app.base.BaseActivity
import com.gombe.credit.app.event.GombeCreditEventData
import com.gombe.credit.app.event.GombeCreditEventPointHelper
import com.gombe.credit.app.event.GombeCreditEventSubscriber
import com.gombe.credit.app.request.HttpHelper
import com.gombe.credit.app.request.IHttpCallback
import com.gombe.credit.app.request.NetworkErrorManager
import com.gombe.credit.app.ui.dialog.DialogGombeCreditCustomer
import com.gombe.credit.app.ui.dialog.DialogGombeCreditReload
import com.gombe.credit.app.ui.dialog.DialogGombeCreditTips
import com.gombe.credit.app.utils.log.GombeCreditLogger
import org.json.JSONObject
import pub.devrel.easypermissions.EasyPermissions

/**
 * CommonActivity
 * @Author wwdeng
 * @CreateTime: 2024/11/20 10:32
 * @Annotation：
 */
abstract class CommonActivity: BaseActivity(), GombeCreditEventSubscriber, ICommonView,EasyPermissions.PermissionCallbacks {
    var errorDialog: DialogGombeCreditTips? = null

    var netErrorDialog: DialogGombeCreditReload? = null
    //错误提示显示次数
    private var showErrorCount = 0

    override fun getAct(): CommonActivity {
        return this
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        NetworkErrorManager.registerActivity(this)
    }

    override fun onStart() {
        super.onStart()
//        HttpHelper.setTag(this)
        GombeCreditApp.app.publisher.register(this)
    }

    /**
     * 错误提示
     */
    fun showErrorTipsDialog(tips: String,eventRemark: String = ""){
        if (errorDialog == null){
            errorDialog = DialogGombeCreditTips(this,eventRemark)
        }
        errorDialog?.let { dialog ->
            if (dialog.isShowing){
                return
            }
            dialog.setOnClick(object : DialogGombeCreditTips.IDialogCallback{
                override fun onClick(view: View?) {

                }
            })
            dialog.show()
            dialog.isGombeCreditKindTipsDoubleButton(false)
            dialog.setGombeCreditKindTipsMsgText(tips)
        }
    }

    /**
     * 客服
     */
    fun showCustomerDialog(eventRemark: String = "",pName: String = "", pToken: String = ""){
        DialogGombeCreditCustomer(this)
            .setGombeCreditCustomerCancelable(true)
            .setGombeCreditCustomerCanceledOnTouchOutside(true)
            .setGombeCreditCustomerProductName(pName)
            .setGombeCreditCustomerProductToken(pToken)
            .setGombeCreditCustomerEventRemark(eventRemark)
            .setGombeCreditCustomerClickCallback(object : DialogGombeCreditCustomer.IDialogCallback{
                override fun onGombeCreditCallPhoneClick(phoneNumber: String) {
                }
                override fun onGombeCreditCopyEmailClick(email: String) {
                }
                override fun onGombeCreditFeedbackClick() {//Feedback
                }
            })
            .show()
    }

    /**
     * 接口请求失败提示
     */
    fun showRequestErrorDialog(errorData: JSONObject){
        if (errorDialog == null){
            errorDialog = DialogGombeCreditTips(this)
        }
        errorDialog?.let {
            if (it.isShowing){
                return
            }
            it.setOnClick(object : DialogGombeCreditTips.IDialogCallback{
                override fun onClick(view: View?) {
                    if (view?.id == R.id.buttonConfirm){
                        requestTryAgain()
                    }
                }
            })
            it.addGombeCreditKindTipsEventRemark("network error")
            it.setCancelable(true)
            it.setCanceledOnTouchOutside(false)
            it.show()
            it.isGombeCreditKindTipsDoubleButton(true)
            it.setGombeCreditKintTipsButtonConfirmText(getString(R.string.gombe_credit_button_try_again))
            it.setGombeCreditKindTipsMsgText(getString(R.string.gombe_credit_dialog_loading_failed))
        }
    }

    fun showGombeCreditGlobalErrorDialog(onReloadClick: () -> Unit, onDismissListener: () -> Unit): DialogGombeCreditReload?{
        if (netErrorDialog == null){
            netErrorDialog = DialogGombeCreditReload(this,"",object : DialogGombeCreditReload.IDialogCallback{
                override fun onClick(view: View?) {
                    showGombeCreditLoading()
                    onReloadClick.invoke()
                }
            })
            netErrorDialog?.setOnDismissListener {
                onDismissListener.invoke()
            }
            netErrorDialog?.setCancelable(false)
            netErrorDialog?.setCanceledOnTouchOutside(false)
        }
        var showErrorMsg = getString(R.string.gombe_credit_dialog_loading_failed)
        if (showErrorCount >= 3){
            showErrorMsg = getString(R.string.gombe_credit_dialog_loading_check)
        }
        netErrorDialog?.let { dialog ->
            if (!isFinishing && !isDestroyed && !dialog.isShowing){
                dialog.show()
                dialog.setGombeCreditKindTipsMsgText(showErrorMsg)
                showErrorCount += 1
            }
        }
        return netErrorDialog
    }

    /**
     * post
     */
    fun doPostAction(httpUrl: String,params: JSONObject,callback: IHttpCallback){
        HttpHelper.post(httpUrl,params,object : IHttpCallback {
            override fun onRequestSuccess(data: JSONObject) {
                callback.onRequestSuccess(data)
            }

            override fun onRequestError(error: JSONObject) {
                callback.onRequestError(error)
                showGombeCreditToast(error.optString("errorMsg"))
            }

            override fun onRequestFinish() {
                callback.onRequestFinish()
            }
        })
    }

    /**
     * 添加埋点
     */
    fun addEventPointRequestAction(eventName: String, eventRemark: String? = "") {
        GombeCreditEventPointHelper.addEventPointRequestAction(eventName,eventRemark)
    }

    /**
     * 发送事件通知
     */
    fun publishEventData(eventData: GombeCreditEventData){
        GombeCreditApp.app.publisher.publish(eventData)
    }

    /**
     * 处理订阅事件
     */
    override fun onGombeCreditPublishEvent(event: GombeCreditEventData) {
    }

    /**
     * 重试
     */
    override fun requestTryAgain() {
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        // 进一步使用 EasyPermissions 处理后续结果
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    /**
     * 用户点击同意授权后会回调该方法
     */
    override fun onPermissionsGranted(requestCode: Int, perms: MutableList<String>) {
        GombeCreditLogger.e("onPermissionsGranted, code: $requestCode , permissions : $perms")
    }

    /**
     * 用户点击拒绝授权后会回调该方法
     */
    override fun onPermissionsDenied(requestCode: Int, perms: MutableList<String>) {
        GombeCreditLogger.e("onPermissionsDenied code: $requestCode , permissions : $perms")
    }

    override fun onDestroy() {
        super.onDestroy()
        NetworkErrorManager.unregisterActivity(this)
        HttpHelper.cancelTag(this)
        GombeCreditApp.app.publisher.detach(this)
    }
}